package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	. "web_api_gin/controller"
	"web_api_gin/core"
	"web_api_gin/dao"
	"web_api_gin/dto"
	"web_api_gin/entity"
	"web_api_gin/service"
)

var SysRoleApi = SysRoleController{}

type SysRoleController struct {
}

//首页列表
func (c *SysRoleController) Index(ctx *gin.Context) {
	var searchParams dto.SysRoleGetListReq
	if err := ctx.ShouldBind(&searchParams); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//角色列表
	roleList, total, err := dao.SysRole.GetList(ctx, &searchParams)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, err.Error())
		return
	}
	//角色树结构里欸哦奥
	var roleTreeList []*dto.SysRoleTree
	if searchParams.Name == "" && searchParams.DisplayName == "" {
		roleTreeOriginList := ([]*dto.SysRoleTree)(nil)
		for _, role := range roleList {
			roleTreeOriginList = append(roleTreeOriginList, &dto.SysRoleTree{
				SysRole: *role,
			})
		}
		roleTreeList = service.SysRole.BuildTree(roleTreeOriginList)
	} else {
		for _, role := range roleList {
			roleTreeList = append(roleTreeList, &dto.SysRoleTree{
				SysRole: *role,
			})
		}
	}
	//权限列表
	permList, err := dao.SysPermission.GetAll(ctx)
	permTreeOriginList := ([]*dto.SysPermissionTree)(nil)
	for _, permission := range permList {
		permTreeOriginList = append(permTreeOriginList, &dto.SysPermissionTree{
			SysPermission: *permission,
		})
	}
	permTreeList := service.SysPermission.BuildTree(permTreeOriginList)
	//显示输出
	Success(ctx, gin.H{
		"roleList": roleTreeList,
		"total":    total,
		"permList": permTreeList,
	})
}

//保存角色数据
func (c *SysRoleController) Save(ctx *gin.Context) {
	var form *entity.SysRole
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	if err := dao.SysRole.SaveRole(ctx, form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
		return
	}
	Success(ctx, gin.H{})
}

//删除角色
func (c *SysRoleController) Destroy(ctx *gin.Context) {
	var form *dto.SysRoleFormDestroy
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	err := dao.SysRole.DelRole(ctx, form.RoleIds)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
		return
	}
	Success(ctx, gin.H{})
}
